import 'dart:async';

import 'package:get/get.dart';
import 'package:psi/base/base_controller.dart';
import 'package:psi/entity/request/register_req.dart';
import 'package:psi/entity/common_resp.dart';
import 'package:psi/entity/response/login_resp.dart';
import 'package:psi/http/api_service.dart';
import 'package:psi/utils/utils.dart';

import '../login/login_logic.dart';
import 'register_state.dart';

class RegisterLogic extends BaseController {
  final RegisterState state = RegisterState();
  final loginState = Get.find<LoginLogic>().state;

  Timer? _timer;
  int count = 60;

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
    _timer?.cancel();
  }

  void sendCode() {
    state.getCode.value = true;
    _timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
      if (count == 1) {
        state.getCode.value = false;
        state.codeBtnTitle.value = "获取验证码";
        count = 60;
        _timer?.cancel();
        _timer = null;
      } else {
        count--;
        state.codeBtnTitle.value = "重新获取（$count）";
      }
    });
  }

  void goToLogin() {
    Get.back();
  }

  void registerAction() async {
    if (!loginState.read.value) {
      showToast("请阅读并同意用户协议和隐私政策");
      return;
    }
    if (state.req.value.account?.isEmpty ?? true) {
      showToast("请输入用户名");
      return;
    }
    if (state.req.value.phone?.isEmpty ?? true) {
      showToast("请输入手机号");
      return;
    }
    if (state.req.value.code?.isEmpty ?? true) {
      showToast("请输入验证码");
      return;
    }
    if (state.req.value.password?.isEmpty ?? true) {
      showToast("请输入密码");
      return;
    }
    if (state.repeatPassword.value != state.req.value.password) {
      showToast("两次密码输入不一致");
      return;
    }
    try {
      showLoading();
      LoginResp resp = await ApiService.request.register(state.req.value);
      if (resp.code == 0) {
        Utils.userLogic.loginSuccess(resp);
      } else {
        showToast(resp.message);
      }
      hideLoading();
    } catch(e) {
      Utils.logE(e);
      hideLoading();
    }
  }
}
